define(['moment','jqplot-bar','jqplot-pointLabels','jqplot-pie',
'module/system/service/WatchDogService',
'module/moduleSMT/program/SMT17/materialNeed.service'
], function (moment) {
    return ['$rootScope', '$scope', '$filter', '$stateParams', 'config', 'MMWService', '$timeout', '$calculater', 'WatchDogService','$MaterialNeed',
        function ($rootScope, $scope, $filter, $stateParams, config, $MMWService, $timeout, $calculater, $WatchDogService,$MaterialNeed) {
            var delay_timer;
            $scope.init = function(){
                $scope.data = {};
                var _SMT17_init = localStorage.getItem(config.appName + '_SMT17_init');
                
                if(_SMT17_init){
                    $scope.data = JSON.parse(_SMT17_init);
                    $scope.data.produce_qty = 0
                    $scope.data.type = 1;
                    $scope.A1PanelSwitch = '0';
                } else{
                    $scope.data = {
                        type:0,
                        mode:0,
                        area_no: '',
                        op_no: '',
                        seq: '',
                        machine_no: '',
                        plot_no:'',
                        produce_qty:0
                    };
                    $scope.A1PanelSwitch = '0';
                }
                //取系統參數MSD
                $scope.mtrl_chart = '1';
                $scope.MSD = config.cache.sys_parameter['SMTInfo.MSD']
                $scope.item_list = [];
                $scope.time_over = false;
                $scope.current_post_qty = 0;//画面上已过账成功数量
                $scope.feeder__empty = false;//有料站口未上feeder
            };

            var dog = {
                bark:function(feed, next){
                    $scope.callDashboardData(next,next == undefined);
                }
            };

            $scope.final = function(callback){
                if(refresh_timer_for_draw != undefined){
                    $timeout.cancel(refresh_timer_for_draw);
                    refresh_timer_for_draw = undefined;
                }
                if(refresh_timer_for_redraw != undefined){
                    $timeout.cancel(refresh_timer_for_redraw);
                    refresh_timer_for_redraw = undefined;
                }

                if(dog_watch != undefined){
                    $timeout.cancel(dog_watch);
                    dog_watch = undefined;
                }

                $WatchDogService.stopWatch();
                if(typeof callback === 'function')
                    callback();
            }

            $scope.back = function(){
                $scope.$root.hideMenu();
                $scope.final(function(){
                     $scope.$root.changeProgram('home', true)
                })
            };

            $scope.change_pro_bar = function(info){
                $scope.A1PanelSwitch = info
            }
            
            // 選擇區域 (開窗)
            $scope.loadAreaList = function () {
                $MMWService.showQueryListPNIG({
    				page_mode: 'smt_area_info_get',
                    key: 'area_no',
                    header: [
                        {label:$filter('translate')('common.queryList.area_c'), code:'area_no'},
                        {label:$filter('translate')('common.queryList.area_n'), code:'area_name'}
                    ],
                    setCondition: function (conditions) {
                        conditions.push({ column_name: 'A.LOTNO', query_mode: '0', value: $scope.data.plot_no, merge_condition_model: 'AND' });
                        return conditions;
                    },
                    confirm:function(selectItem, dialog){
                        dialog.hide();
                        $scope.data.area_no = selectItem.area_no;
                        $scope.data.op_no = '';
                        $scope.data.seq = '';
                        $scope.data.machine_no = '';
                        $scope.loadOpNoList();
                    }
                });
            };

            // 選擇作業站 (開窗)
            $scope.loadOpNoList = function () {
                if($scope.area_no != ''){
                    $MMWService.showQueryListPNIG({
                        page_mode:'smt_area_op_info_get',
                        key: 'op_no',
                        header: [
                            {label:$filter('translate')('common.queryList.op_c'), code:'op_no'},
                            {label:$filter('translate')('common.queryList.op_n'), code:'op_name'}
                        ],
                        setCondition: function (conditions) {
                            conditions.push({ column_name: 'A.LOTNO', query_mode: '0', value: $scope.data.plot_no, merge_condition_model: 'AND' });
                            conditions.push({ column_name: 'd.AreaNo', query_mode: '0', value: $scope.data.area_no, merge_condition_model: 'AND' });
                            return conditions;
                        },
                        confirm:function(selectItem, dialog){
                            dialog.hide();
                            $scope.data.op_no = selectItem.op_no;
                            $scope.data.seq = '';
                            $scope.data.machine_no = '';
                            $scope.loadseqList();
                        }
                    });
                }
            };

            //取得工具訊息
            function tool_usage_info_get(){
                $MMWService.sendToServer({
                    uri: 'ServicesSMT.Module_SMT.tool_usage_info_get',
                    content: {
                        type: $scope.data.type,
                        equipment_no: $scope.data.machine_no,
                        panel_side: $scope.data.panel_side,
                        plot_no: $scope.data.plot_no,
                        seq: $scope.data.seq,
                        area_no: $scope.data.area_no,
                        op_no: $scope.data.op_no
                    },
                    success: function (data) {
                         $scope.info_list = data.tool_list;
                    }
                });
            }

            $scope.switchMtrlChart = function(page){
                $scope.mtrl_chart = page;
                $scope.callDashboardData()
            }

            $scope.callMaterial_Demand_status = function(){
                $MMWService.sendToServer({
                    uri: 'ServicesSMT.Module_SMT.mtl_request_status_info_get',
                    content: {
                        eqp_no:$scope.data.machine_no
                    },
                    success: function (data) {
                         $scope.mtrl_list = data.pick_list;
                         $scope.mtrl_list.forEach(function(item){
                            item.time_stamp = moment(new Date()).format('YYYY-MM-DD HH:mm:ss');
                         }) 
                    }
                });
            }

            //取得物料訊息
            function material_info_get(){
                $MMWService.sendToServer({
                    uri: 'ServicesSMT.Module_SMT.material_info_get',
                    content: {
                        type: $scope.data.type,
                        equipment_no: $scope.data.machine_no,
                        panel_side: $scope.data.panel_side,
                        plot_no: $scope.data.plot_no,
                        seq: $scope.data.seq,
                        area_no: $scope.data.area_no,
                        op_no: $scope.data.op_no
                    },
                    success: function (data) {
                         $scope.info_list = data.material_list;
                         $scope.feeder__empty = $scope.info_list.some(item=>(item.is_material_done=='1'))
                    }
                });
            }
            let gb_chart;//良與不良圖表
            //取得良品與不良品數
            function check_qty_info_get(){
                $MMWService.sendToServer({
                    uri: 'ServicesSMT.Module_SMT.check_qty_info_get',
                    content: {
                        type: $scope.data.type,
                        equipment_no: $scope.data.machine_no,
                        panel_side: $scope.data.panel_side,
                        plot_no: $scope.data.plot_no,
                        seq: $scope.data.seq,
                        area_no: $scope.data.area_no,
                        op_no: $scope.data.op_no,
                        before_op_seq:$scope.data.before_op_seq,
                    },
                    success: function (data) {
                        let arr = [[$filter('translate')('SMT17.good_qty'),(+data.good_qty)], [$filter('translate')('SMT17.scrap_qty'),(+data.scrap_qty)]]
                        $('#chart1').empty(); // 為了避免重疊，每呼叫一次長條圖要先刪除當下的長條圖後，再產生出新的長條圖
                        $('#chart1').css('flex', '1').css('min-height', '100%');
                        gb_chart='';
                        gb_chart = $.jqplot('chart1', [ arr ],
                            {
                            title:{         // 標題屬性
                                text:`<div class="chart-title">${$filter('translate')('SMT17.qty_sum')}<div>`,           // 標題文字
                                show:true,              // 是否陰影
                                // fontFamily:'微軟雅黑',  標題字型 
                                fontSize:18,            // 標題字型大小
                                fontWeight:'bold',
                                textAlign:'left',       // 標題對齊方式
                                textColor:'#515151',    // 標題顏色（也可以寫作屬性color）
                                escapeHtml:false        // 是否轉義HTML字元，值為false時，可以在text屬性中使用HTML程式碼
                            },
                            animate: !$.jqplot.use_excanvas,
                            seriesDefaults:{
                                renderer:$.jqplot.BarRenderer,
                                pointLabels:{show:true,location:'n',edgeTolerance:-15},
                                shadowAngle:false,
                                shadow:false,
                                rendererOptions:{
                                    barMargin: 50,
                                    highlightMouseDown: true,  
                                    // barDirection:'horizontal'
                                }
                            },
                            axes:{
                                //X軸
                                xaxis: {
                                    renderer: $.jqplot.CategoryAxisRenderer,
                                }
                            }
                        });
                    },
                    error: function (data) {
                        $scope.data.posted_qty = 0;
                    }
                });
            }

            let effect_arr = [];
            let origin_effect_qty;
            let effect_chart;
            function getEfficiencyChart(){
                let content = {
                    type: $scope.data.type,
                    equipment_no: $scope.data.machine_no,
                    panel_side: $scope.data.panel_side,
                    plot_no: $scope.data.plot_no,
                    seq: $scope.data.seq,
                    area_no: $scope.data.area_no,
                    op_no: $scope.data.op_no
                };
                $MMWService.sendToServer({
                    uri: 'ServicesSMT.Module_SMT.produce_efficiency_info_get',
                    content: content,
                    success: function (data) {
                        $('#efficiency_chart').empty();
                        effect_chart = '';
                        effect_arr=[];//每呼叫一次服務就清掉圖表資料重新倒入
                        data.efficiency_list.forEach(function(item){
                            effect_arr.push([item.x,( + item.y )]);
                        })
                        effect_chart = $.jqplot('efficiency_chart',[effect_arr],
                            {
                            title:{         // 標題屬性
                                text:`<div class="chart-title">${$filter('translate')('SMT17.produce_efficiency')}<div>`,           // 標題文字
                                show:true,              // 是否陰影
                                fontFamily:'Roboto, "Helvetica Neue", "Microsoft JhengHei", sans-serif;',  // 標題字型 
                                fontSize:18,            // 標題字型大小
                                fontWeight:'900',
                                textAlign:'left',       // 標題對齊方式
                                textColor:'#515151',    // 標題顏色（也可以寫作屬性color）
                                escapeHtml:false        // 是否轉義HTML字元，值為false時，可以在text屬性中使用HTML程式碼
                            },
                            animate: !$.jqplot.use_excanvas,
                            seriesDefaults:{
                                renderer:$.jqplot.BarRenderer,//資料以長條圖的方式呈現
                                pointLabels:{show:true,location:'s',edgeTolerance:10},
                                shadow:false,
                                shadowAngle:false,
                                rendererOptions:{
                                    barMargin: 10,
                                    highlightMouseDown: true,  
                                    // barDirection:'horizontal'
                                }
                            },
                            grid: {
                                drawBorder: false, 
                                // drawGridlines: false,
                                background: '#fff',
                                shadow:false
                            },
                            axes:{
                                //X軸
                                xaxis: {
                                    renderer: $.jqplot.CategoryAxisRenderer,
                                }
                            }
                        });
                    }
                });
            }

            function get_temp_eff_chart(){
                $('#efficiency_chart').empty();
                effect_chart = '';
                effect_chart = $.jqplot('efficiency_chart',[effect_arr],
                    {
                    title:{         // 標題屬性
                        text:`<div class="chart-title">${$filter('translate')('SMT17.produce_efficiency')}<div>`,           // 標題文字
                        show:true,              // 是否陰影
                        fontFamily:'Roboto, "Helvetica Neue", "Microsoft JhengHei", sans-serif;',  // 標題字型 
                        fontSize:18,            // 標題字型大小
                        fontWeight:'900',
                        textAlign:'left',       // 標題對齊方式
                        textColor:'#515151',    // 標題顏色（也可以寫作屬性color）
                        escapeHtml:false        // 是否轉義HTML字元，值為false時，可以在text屬性中使用HTML程式碼
                    },
                    animate: !$.jqplot.use_excanvas,
                    seriesDefaults:{
                        renderer:$.jqplot.BarRenderer,//資料以長條圖的方式呈現
                        pointLabels:{show:true,location:'s',edgeTolerance:10},
                        shadowAngle:false,
                        shadow:false,
                        rendererOptions:{
                            barMargin: 10,
                            highlightMouseDown: true,  
                            // barDirection:'horizontal'
                        }
                    },
                    grid: {
                        drawBorder: false, 
                        // drawGridlines: false,
                        background: '#fff',
                        shadow:false
                    },
                    axes:{
                        //X軸
                        xaxis: {
                            renderer: $.jqplot.CategoryAxisRenderer,
                        }
                    }
                });
            }
        
            // 選擇加工序 (開窗)
            $scope.loadseqList = function () {
                if($scope.area_no != ''){
                    $scope.$root.showQueryList({
                        key: 'seq',
                        pageRecord: 50,
                        header: [
                            { label: $filter('translate')('SMT17.queryList.seq'), code: 'seq' },
                            { label: $filter('translate')('SMT17.queryList.seq_remark'), code: 'description' },
                            { label: $filter('translate')('SMT17.queryList.machine_no'), code: 'equipment_no' },
                            { label: $filter('translate')('SMT17.queryList.machine_name'), code: 'equipment_name' },
                            { label: $filter('translate')('SMT17.queryList.need_posting'), code: 'need_posting' },
                            { label: $filter('translate')('SMT17.queryList.posting_source_type'), code: 'posting_source_type_show' },
                            { label: $filter('translate')('SMT17.queryList.allow_duplicate_posting'), code: 'allow_duplicate_posting_show' },
                            { label: $filter('translate')('SMT17.queryList.before_op_seq'), code: 'before_op_seq' },
                            { label: $filter('translate')('SMT17.queryList.time_interval'), code: 'time_interval' }
                        ],
                        query: function (conditions, feedback) {
                            var query_condition_info = [
                                { column_name: 'd.AREANO', query_mode: '0', value: $scope.data.area_no, merge_condition_model: 'AND' },
                                { column_name: 'x.ORGLOTNO', query_mode: '0', value: $scope.data.plot_no, merge_condition_model: 'AND' }
                            ];
                            $MMWService.pageNumberInfoGet({
                                page_mode: 'smt_area_seq_info_get',
                                query_condition_info: query_condition_info
                            }, function (itemList) {
                                for (var i = 0; i < itemList.length; i++) {
                                    if (itemList[i].need_posting == 1) {
                                        itemList[i].need_posting = $filter('translate')('SMT17.queryList.need');
                                    } else {
                                        itemList[i].need_posting = $filter('translate')('SMT17.queryList.no_need');
                                    };
                                    if (itemList[i].posting_source_type == 1) {
                                        itemList[i].posting_source_type_show = $filter('translate')('SMT17.queryList.panel_no');
                                    } else if(itemList[i].posting_source_type ==2) {
                                        itemList[i].posting_source_type_show = $filter('translate')('SMT17.queryList.pcs_no');
                                    };
                                    if (itemList[i].allow_duplicate_posting == 1) {
                                        itemList[i].allow_duplicate_posting_show = $filter('translate')('SMT17.queryList.yes');
                                    } else {
                                        itemList[i].allow_duplicate_posting_show = $filter('translate')('SMT17.queryList.no');
                                    };
                                };
                                feedback(itemList);
                            });
                        },
                        selectCode: $scope.data.seq,
                        confirm: function (selectItem, dialog) {
                            if (selectItem.need_posting == $filter('translate')('SMT17.queryList.no_need')) {
                                $scope.$root.showAlert($filter('translate')('SMT17.msg.no_need_posting'));
                            } else {
                                dialog.hide();
                                $scope.data.op_prop = selectItem.op_prop;//20201020 add by Oliver for 作業站屬性
                                $scope.data.seq = selectItem.seq;
                                $scope.data.seq_remark = selectItem.description;
                                $scope.data.machine_no = selectItem.equipment_no;
                                $scope.data.posting_source_type = selectItem.posting_source_type;
                                $scope.data.panel_side = selectItem.panel_side;
                                $scope.data.allow_duplicate_posting = selectItem.allow_duplicate_posting;
                                $scope.data.before_op_seq = selectItem.before_op_seq;//20201117工序管理新增
                                $scope.data.time_interval = selectItem.time_interval;
                                $scope.data.feederlist_no = selectItem.feederlist_no;
                                $scope.data.feederlist_ver = selectItem.feederlist_ver;
                            }
                        }
                    });
                }
            };

            //生产批开窗
            $scope.loadPlotList = function () {
                $MMWService.showQueryListPNIG({
                    page_mode: 'smt_lot_info_get',
                    key: 'plot_no',
                    header: [
                        { label: $filter('translate')('common.queryList.plot_no'), code: 'plot_no' }
                    ],
                    confirm: function (selectItem, dialog) {
                        dialog.hide();
                        $scope.data.plot_no = selectItem.plot_no;
                        $scope.data.product_no = selectItem.product_no;
                        $scope.data.item_spec = selectItem.item_spec;
                        $scope.data.area_no = '';
                        $scope.data.op_no = '';
                        $scope.data.seq = '';
                        $scope.data.machine_no = '';

                        PlotAreaOPInfoGet(selectItem.plot_no);

                    }
                });
            };

            //取得生产批对应区域和作业站
            function PlotAreaOPInfoGet(plot_no) {
                $MMWService.sendToServer({
                    uri: 'ServicesSMT.Module_SMT.plot_area_op_info_get',
                    content: {
                        plot_no: plot_no
                    },
                    success: function (data) {
                        $scope.data.area_no = data.area_no;
                        $scope.data.op_no = data.op_no;
                    }
                });
            }
            
            $scope.callDashboardData = function(callback){
                if($scope.page_mode == 'next_page'){
                    mater__tool();//生產效率表刷新
                    if($scope.data.op_prop == '4'){
                        check_qty_info_get();
                    }else if($scope.data.op_prop == '2' || $scope.data.op_prop == '3'){
                        if($scope.mtrl_chart == '1'){
                             getEfficiencyChart();
                        }else if($scope.mtrl_chart == '2'){
                            $scope.callMaterial_Demand_status();
                        }
                    }
                    if(callback)
                        callback();
                }
            }
            
            function mater__tool(){//物料信息、工具訊息表重刷新
                if($scope.data.op_prop === '2'){
                    tool_usage_info_get();
                }else if($scope.data.op_prop === '3'){
                    material_info_get();
                }
            }
            let refresh_timer_for_draw;
            function draw__chart(){
                refresh_timer_for_draw = $timeout(function(){//display:block要出現才去渲染canvas，所以要$timeout
                    if($scope.data.op_prop == '4'){
                        check_qty_info_get();
                    }else if($scope.data.op_prop == '2' || $scope.data.op_prop == '3'){
                        getEfficiencyChart();
                        // get_temp_eff_chart()
                    }
                },100);
            }
            let refresh_timer_for_redraw;
            function redraw__chart(){
                refresh_timer_for_redraw = $timeout(function(){//display:block要出現才去渲染canvas，所以要$timeout
                    if($scope.data.op_prop == '4'){
                        check_qty_info_get();
                    }else if($scope.data.op_prop == '2' || $scope.data.op_prop == '3'){
                        get_temp_eff_chart()
                    }
                },100);
            }
            let dog_watch;
            //進入過帳畫面
            $scope.confirm = function(){
                if($scope.data.seq != undefined){//20200608 add by Oliver for 没有加工序卡控
                    if($scope.data.op_prop == ''){//如果該工序作業站屬性未設定
                        $scope.$root.showAlert($filter('translate')('SMT17.msg.op_prop_empty'));
                    }else{
                        $scope.page_mode = 'next_page'
                        $scope.data.posted_qty = 0;
                        $scope.current_post_qty = 0;
                        $scope.data.mode = '';
                        $scope.item_list = [];
                        mater__tool();

                        localStorage.setItem(config.appName + '_SMT17_init', JSON.stringify($scope.data));
                        lot_panel_info_get();
                        draw__chart();//繪製圖表
                        $scope.data.produce_qty = 0;
                        delay_timer = moment().get('seconds');
                        delay_timer = 1000*(60 - delay_timer);
                        dog_watch = $timeout(function(){
                            $WatchDogService.startWatch(dog, true);//WatchDog
                        },delay_timer);
                        $scope.data.type = 1;//進入畫面預設為PASS
                    }
                }else{
                    $scope.$root.showAlert($filter('translate')('SMT17.msg.select_seq_plz'));
                }
            }

            // 進入設定畫面
            $scope.settings = function(){
                $scope.page_mode = '';
                effect_chart = '';//清除生產效率圖表
                gb_chart='';//清除良品不良品圖表
                clearInterval($rootScope.timeEnd);
                $scope.A1PanelSwitch = '0';
                $scope.mtrl_chart = '1';
                $scope.data.type = 1;
                $scope.data.work_no = ''; 
                $scope.data.work_no_qty = 0;
                $scope.data.produce_qty = 0;
                $scope.final()
            }

            // QRCode輸入
            $scope.QRCodeScanner = function(){
                $scope.$root.OpenScanner({
                    after : function(result){
                        $scope.input_barcode(result.text);
                    },
                    exception: function(){
                        //目前裝置無法使用相機
                        $scope.$root.showAlert($filter('translate')('B0214.showAlert.column3'));
                    },
                    orientation : 'landscape'
                });
            };
            function partial_info_get(barcode){
				var over_counts = false;
				if($scope.info_list== undefined){
				    over_counts = false;
				}else{
                    if($scope.data.op_prop=='2'){
                        over_counts = $scope.info_list.some(function(item){
                            return item.color == 'r';
                        })
                    }else if($scope.data.op_prop=='3'){
                        over_counts = $scope.info_list.some(function(item){
                            return item.mtl_alarm == 'r';
                        })
                    }
				}

                if(over_counts){
                    if($scope.data.op_prop=='2'){//印刷機工具使用次數預警
                        $scope.$root.showAlert($filter('translate')('SMT17.msg.tool_over_used'));
                    }else if($scope.data.op_prop=='3'){//貼片機物料預警
                        $scope.$root.showAlert($filter('translate')('SMT17.msg.material_empty'));
                    }
                }else{
                    $MMWService.sendToServer({
                        uri:'ServicesSMT.Module_SMT.partial_info_get',
                        content : {
                            type:$scope.data.type,
                            equipment_no:$scope.data.machine_no,
                            input_no: barcode,
                            panel_side: $scope.data.panel_side,
                            plot_no: $scope.data.plot_no,
                            seq: $scope.data.seq,
                            area_no: $scope.data.area_no,
                            line_body:$scope.data.area_no,
                            op_no: $scope.data.op_no,
                            posting_source_type: $scope.data.posting_source_type,
                            allow_duplicate_posting: $scope.data.allow_duplicate_posting,
                            op_prop:$scope.data.op_prop,
                            before_op_seq:$scope.data.before_op_seq ||'0',
                            time_interval:$scope.data.time_interval ||'0'
                        },
                        success: function(data){
                            $scope.data.produce_qty += 1;//生產數量
                            $scope.data.work_no = data.work_no;
                            $scope.data.work_no_qty = data.work_no_qty;
                            if(data.pcs_list && data.pcs_list.length > 0){
                                $scope.data.mode = data.mode;
                                $scope.data.plot_no = data.lot_no;
                                $scope.data.product_no = data.product_no;
                                $scope.data.item_spec = data.item_spec;
                                $scope.data.qty = data.pcs_count;
                                $scope.data.posted_qty = data.posted_qty;
                                $scope.data.pcs_no = data.pcs_no;
                                $scope.data.remain_time = data.remain_time;//20200928 add by Oliver for 新增剩餘時間
                                $scope.data.slot_no = data.slot_no;//20200928 add by Oliver for 新增剩餘時間
                                $scope.data.reel_no = data.reel_no;//20200928 add by Oliver for 新增剩餘時間

                                if($scope.data.remain_time != '-1' && $scope.MSD !='1'){
                                    if($scope.data.remain_time <= 30 && $scope.data.remain_time >0){
                                        $rootScope.showAlert($filter('translate')('SMT17.msg.in_time_period',{slot_no:$scope.data.slot_no, reel_no:$scope.data.reel_no}));
                                    }else if($scope.data.remain_time <= 0 ){
                                        $rootScope.showAlert($filter('translate')('SMT17.msg.over_time',{slot_no:$scope.data.slot_no, reel_no:$scope.data.reel_no}));
                                        $('#toast-panel').addClass('error');
                                        $scope.time_over = true;
                                    }
                                }

                                if($scope.data.pcs_no && $scope.data.posting_source_type == 1){//add by Oliver for M#74102 [鑫森海SMT]BETA-SMT段报工扫码方式:[標準][修改]SMT產品過帳
                                    let pcs_no_arr = $scope.data.pcs_no.split(';');
                                    $scope.data.pcs_no = pcs_no_arr[0] + ' ~ ' + pcs_no_arr[pcs_no_arr.length - 1];
                                }
                                //$scope.qty = data.qty;
                                //data.pcs_list.forEach(function(pcs_item, index){
                                for(var i = 0; i < data.pcs_list.length; i++){
                                    var pcs_item = data.pcs_list[i];
                                    pcs_item.index = $scope.item_list.length;
                                    pcs_item.op_no = $scope.data.op_no;
                                    pcs_item.plot_no = $scope.data.plot_no;
                                    pcs_item.equipment_no = $scope.data.machine_no;
                                    pcs_item.pcs_no = $scope.data.pcs_no;
                                    pcs_item.rightNow = moment(new Date()).format('YYYY/MM/DD/HH:mm:ss');
                                    pcs_item.user_name = config.cache.name;
                                    $scope.item_list.push(pcs_item);
                                    // 20200108 modify by WeiTing for M#66213 - 跟 SA 和 後端 確認過後，拿掉卡控，改成每個加工序刷入的序號都各自獨立進行。
                                    // if(pcs_item.status == 'R'){
                                    //     pcs_item.status = 'Fail';
                                    //     pcs_item.remark = $filter('translate')('SMT17.msg.seq_aready_ng');
                                    //     data.pcs_list.splice(i, 1);
                                    //     i--;
                                    // } else if(pcs_item.status == 'D'){
                                    //     pcs_item.status = 'Fail';
                                    //     pcs_item.remark = $filter('translate')('SMT17.msg.seq_aready_pass');
                                    //     data.pcs_list.splice(i, 1);
                                    //     i--;
                                    // }    
                                };
                                if(data.pcs_list.length > 0){
                                    panel_info_set_process(data);
                                }
                            } else {
                                $scope.item_list.push({
                                    index:$scope.item_list.length,
                                    pcs_no: barcode,
                                    panel_no: '',
                                    status: 'Fail',
                                    remark: $filter('translate')('common.msg.no_data'),
                                    right_now: moment(new Date()).format('YYYY/MM/DD/HH:mm:ss')
                                });
                            }
                        },
                        error: function (data) {
                            $scope.item_list.push({
                                index: $scope.item_list.length,
                                pcs_no: barcode,
                                panel_no: barcode,
                                status: 'Fail',
                                remark: data.Message,
                                user_name:config.cache.name,
                                right_now: moment(new Date()).format('YYYY/MM/DD/HH:mm:ss')
                            });
                        }
                    });
                }
            }

            $scope.open_material_need = function(){
                $MaterialNeed.init({
                    title:$filter('translate')('SMT17.material_need_dialog.title'),
                    info_list:$scope.data,
                })
            }

            // 查詢
            $scope.input_barcode = function(barcode){
                $('#toast-panel').css("background-color","#f2ba11");
                function normal_processure(){
                    let banSearch = $scope.info_list.some(item =>((+item.msd_status) <= 0 && item.msd_status != '-0.1'))//有物料MSD超時
                    let harsh = $scope.info_list.some(item =>((+item.msd_status) <= 30 && (+item.msd_status) > 0))//有物料MSD時間介於0-30分鐘之間
                    let letGo = $scope.info_list.some(item=>((+item.msd_status) <= 60 && (+item.msd_status) > 30))//有物料MSD時間介於30-60分鐘之間
                    if($scope.MSD){//有MSD物料管理參數才進管理
                        if(banSearch){//有MSD超時時，顯示警示
                            $('#toast-panel').css("background-color","rgb(219, 75, 60)");
                            $scope.$root.showAlert($filter('translate')('SMT17.msg.MSD_over_time'));
                            return;
                        }else if(harsh){//有物料MSD時間介於0-30分鐘之間，非阻斷式跳窗
                            partial_info_get(barcode);
                            redraw__chart();//數量有更新，刷新效率表
                            $rootScope.showAlertWithoutfocus($filter('translate')('SMT17.msg.MSD_in_a_hurry'));
                            return;
                        }else if(letGo){//有物料MSD時間介於30-60分鐘之間，非阻斷式跳窗
                            partial_info_get(barcode);
                            redraw__chart();//數量有更新，刷新效率表
                            $rootScope.showAlertWithoutfocus($filter('translate')('SMT17.msg.MSD_go_to_over_time'));
                            return;
                        }else{
                            partial_info_get(barcode);
                            redraw__chart();//數量有更新，刷新效率表
                            return;
                        }
                    }else{
                        partial_info_get(barcode);
                        redraw__chart();
                        return;
                    }
                }

                if($scope.data.op_prop=='3' || $scope.data.op_prop=='2'){//此時是貼片機或印刷機
                    if($scope.data.op_prop=='2' && $scope.info_list.length == 0){//如果工具訊息空的不可過站
                        $rootScope.showAlert($filter('translate')('SMT17.msg.no_tool_no_pass'));
                    }else if($scope.data.op_prop=='3'){//貼片機狀態
                        if($scope.info_list.length == 0){//如果沒有物料訊息請使用者設定車間料站表
                            $rootScope.showAlert($filter('translate')('SMT17.msg.info_list_empty'));
                            return;
                        }
                        let feeder_nt_empty = $scope.info_list.some(function(item){return item.feeder_no != null});
                        if(feeder_nt_empty && !$scope.feeder__empty){//已完成上料
                            normal_processure();
                        }else{//1:未上料完成
                            $rootScope.showAlert($filter('translate')('SMT17.msg.u_shouldnt_pass'));
                        }
                    }else{
                        normal_processure();
                    }
                }else{
                    partial_info_get(barcode);
                    redraw__chart();
                }
            };

            function send_partial_info_get_process(content){
                $MMWService.sendToServer({
                    uri:'ServicesSMT.Module_SMT.partial_info_set_process',
                    content: {
                        panel_no: content.panel_no,
                        plot_no: content.lot_no,
                        op_no: content.op_no,
                        product_no: content.product_no,
                        product_ver:content.product_ver,
                        product_version: $scope.data.product_version,
                        area_no: $scope.data.area_no,
                        equipment_no: $scope.data.machine_no,
                        smt_op_seq: $scope.data.seq,
                        panel_side: $scope.data.panel_side,
                        type:$scope.data.type,
                        mode:$scope.data.mode,
                        pcs_list:content.pcs_list
                    },
                    success: function(data){
                        var _status =  $scope.data.type == 2?'NG':'PASS';
                        content.pcs_list.forEach(function(pcs_item){
                            if($scope.data.posting_source_type==1){
                                pcs_item.pcs_no = content.panel_no;
                            }else{
                                pcs_item.pcs_no = content.pcs_no;
                            }
                            pcs_item.status = _status;

                            if(_status == 'PASS'){//如果PASS，則圖表最後一筆項目數量加一
								if(effect_arr.length > 0)
								{
									effect_arr[effect_arr.length-1][1] = effect_arr[effect_arr.length-1][1] + 1; 
								}
                            }

                            pcs_item.user_name = config.cache.name;
                            pcs_item.right_now = moment(new Date()).format('YYYY/MM/DD/HH:mm:ss');
                        });
                        $scope.current_post_qty =  1;

                        if($scope.data.op_prop == '2'){//如果在印刷機作業，工具訊息內的使用次數要遞增
                            $scope.info_list.forEach(function(item){
                                item.acc_count = (+item.acc_count) + 1;
                                let acc_range = (+item.acc_count)/(+item.usage_qty)*100;
                                acc_range = acc_range.toFixed(2);
                                if(( +acc_range) > item.warning_count){
                                    item.color = 'r';
                                }else if(( +acc_range) <= 100 && ( +acc_range) > 60){
                                    item.color = 'y';
                                }else if(( +acc_range) <= 60){
                                    item.color = 'g';
                                }
                            })
                        }else if($scope.data.op_prop == '3'){
                            $scope.info_list.forEach(function(item){
                                item.qty = (+item.qty) - (+item.u_qty)
                                let mtl_range = (+item.qty) / (+item.w_qty)*100;
                                mtl_range = mtl_range.toFixed(2);
                                if(( +mtl_range ) > 60){
                                    item.mtl_alarm = 'g';
                                }else if(( +mtl_range ) <= 60 && ( +mtl_range ) > 30){
                                    item.mtl_alarm = 'y';
                                }else if(( +mtl_range ) <= 30){
                                    item.mtl_alarm = 'r';
                                }
                            })
                        }
                    },
                    error: function(data){
                        content.pcs_list.forEach(function(pcs_item){
                            pcs_item.status = 'Fail';
                            pcs_item.remark = data.Message;
                            pcs_item.name = config.cache.name;
                            pcs_item.right_now = moment(new Date()).format('YYYY/MM/DD/HH:mm:ss');
                        });
                    }
                });
            }

            function panel_info_set_process(content) {
                content.pcs_list.plot_no=content.pcs_list.lot_no;
                delete content.pcs_list.lot_no;
                $scope.current_post_qty = 0;
                if($scope.data.op_prop == '3'){
                    if(checkUqty_over_qty($scope.info_list)){
                        send_partial_info_get_process(content);
                        return;
                    }else{
                        return;
                    }
                }else{
                    send_partial_info_get_process(content);
                }
            }

            function checkUqty_over_qty(list){
                let result = true;
                for(let i = 0; i < list.length; i++){
                    let item = list[i];
                    if((+item.qty) - (+item.u_qty)< 0){
                        result = false;
                        $rootScope.showAlert($filter('translate')('SMT17.msg.u_qty_larger_than_qty',{slot_station:item.position}));
                        break;
                    }
                }
                return result;
            }

            //20200525 linzh add for 查询生产批序号相关信息
            function lot_panel_info_get() {
                $MMWService.sendToServer({
                    uri: 'ServicesSMT.Module_SMT.lot_panel_info_get',
                    content: {
                        type: $scope.data.type,
                        equipment_no: $scope.data.machine_no,
                        panel_side: $scope.data.panel_side,
                        plot_no: $scope.data.plot_no,
                        seq: $scope.data.seq,
                        area_no: $scope.data.area_no,
                        op_no: $scope.data.op_no
                    },
                    success: function (data) {
                        $scope.data.posted_qty = data.posted_qty;
                    },
                    error: function (data) {
                        $scope.data.posted_qty = 0;
                    }
                });
            }
        }
    ];
});
